package telsoft.app.form;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;
import javax.swing.event.*;

import jxl.*;
import telsoft.admin.util.*;
import telsoft.app.util.*;
import telsoft.comm.protocol.*;
import telsoft.swing.*;
import telsoft.util.*;

public class FormISDN extends JXFrame implements ControlButtonListener {
    public JXText ISDN = new JXText();
    public JXText IMSI = new JXText();
    public JXText Name = new JXText();
    public JXText Birthday = new JXText();
    public JXText DateTime = new JXText();
    public JXText Status = new JXText();
    public JXText Address = new JXText();
    public VectorTable tblValue = new VectorTable();
    public PanelControlButton pnlButton;
    public JButton btnReport;
    public FormISDN() throws Exception {
        payInit();
    }

    private void payInit() throws Exception {
        buildForm();
        //Gan gia tri cac truong, button tai form cho cac doi tuong
        ISDN = (JXText) formData.getField("ISDN");
        IMSI = (JXText) formData.getField("IMSI");
	Name = (JXText) formData.getField("Name");
        Birthday = (JXText) formData.getField("Birthday");
	DateTime = (JXText) formData.getField("DateTime");
        Status = (JXText) formData.getField("Status");
	Address = (JXText) formData.getField("Address");
        tblValue = (VectorTable) formData.getControl("tblListDetail");
        btnReport = (JButton) formData.getControl("btnLoad");
        pnlButton = (PanelControlButton) formData.getLayout("ControlButton");
        pnlButton.setNormalState(); //Mac dinh che do hien thi ban dau cua cac controlbutton la an sua xoa
        tblValue.getSelectionModel().
                addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting()) {
                    return;
                }
                fillDetailValue();
            }
        });
        Skin.applySkin(this);
        loadForm();
        onChangeAction(ACTION_NONE, ACTION_NONE); //Mac dinh ban dau action_one = 0
        //Xu ly nhan button import data
        btnReport.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String strMsg = "Dữ liệu trong file excel phai co dang:\n" +
                                "ISDN | IMSI  " +
                                "\n Ban co muon import du lieu khong?";
                int im = MessageBox.showConfirmDialog(FormISDN.this, strMsg,
                        Global.APP_NAME, MessageBox.YES_NO_OPTION);
                if (im == MessageBox.YES_OPTION) {
                    importData(); //Neu nguoi dung chon yes, goi den ham importData()
                }
            }
        });

    }

    public void importData() {
        try {
            String strFilename = Util.openFile(this); //Goi ham openFile nham lay duoc duong dan file xls nguoi dung chon
            if (strFilename != null) { //kiem tra gia tri, neu nguoi dung da chon (tuc strFilename != null)
                Vector vtData = new Vector();
                vtData = getExcelData(strFilename); //goi den ham getExcelData de doc du lieu
                if (vtData == null || vtData.size() < 0) { //kiem tra xem vtdata co gia tri hay khong, tuc file co chua du lieu hay khong
                    return;
                }
//                int iselected = tblValue.getSelectedRow();
//                Vector vtRow = tblValue.getRow(iselected);
//                String strISDN = StringUtil.nvl(vtRow.elementAt(0), "");
                DataTransmit datr = new DataTransmit();
                this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                datr.setVector("mvtData", vtData); //lay ve vector du lieu de truyen sang cho bean
//                datr.setString("mstrISDN", strISDN);
                DataTransmit prmResponse = AppClient.sendRequest(
                        "telsoft.app.bean.ISDNBean",
                        "importData", datr);
                Vector vtErrData = prmResponse.getVector("vtErrData2"); //vterrdata la ben bean day ve vector chua loi
                String strSuccess = prmResponse.getString("isuccess"); //so ban ghi thanh cong
                String strMsg = getDictionary().getString("success") + strSuccess + "/" +
                                vtData.size()+"\n";
                loadForm(); //goi lai ham loadform de xem hien thi
                if (vtErrData.size() > 0) { //Neu co loi thi goi ham writeLogFile trong file Util.java
                    Util.writeLogFile(strFilename.substring(0,
			    strFilename.lastIndexOf(".xls")) + "_" +
				    new java.text.
				    SimpleDateFormat("yyMMddHHmmss").format(new
		    java.util.Date())+ ".txt",
                                      vtErrData);
                    strMsg += getDictionary().getString("Error");
                           // ".\nCó lỗi khi xử lý import. Xem file log cùng thư mục với file danh sách.";
                }
                this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                MessageBox.showMessageDialog(this, strMsg, Global.APP_NAME,
                                             MessageBox.WARNING_MESSAGE);
            }
        } catch (Exception e) {
            MessageBox.showMessageDialog(this, e.getMessage(), Global.APP_NAME);
            this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    }

    public Vector getExcelData(String strFileName) throws Exception { //Lay tung dong du lieu luu vao mang vtData
        Workbook w1 = null;
        String strCellValue = "";
        Cell cell = null;
        Vector vtData = new Vector();
        Vector vtRow = new Vector();
        try {
            w1 = Workbook.getWorkbook(new java.io.File(strFileName));
            Sheet sheet = w1.getSheet(0);
            int iCount = sheet.getRows(); //Lay ve so dong trong file
            for (int i = 0; i < iCount; i++) {
                vtRow = new Vector();
                for (int j = 0; j < 2; j++) {
                    cell = sheet.getCell(j, i); //lay gia tri tung phan tu
                    strCellValue = cell.getContents().trim();
                    vtRow.addElement(strCellValue); //add vao dong
                }
                vtData.addElement(vtRow); //add dong vao vtData
            }
            w1.close();
        } catch (Exception e) {
            e.printStackTrace();
            MessageBox.showMessageDialog(this, e.getMessage(), Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
        }
        return vtData; //tra ve vector
    }

    public void fillDetailValue() {//Day du lieu tu bang vao cac truong tren form khi click chuot
        int iSelected = tblValue.getSelectedRow();
        if (iSelected < 0) {
            clearDetailValue();
            return;
        }
        Vector vtRowData = tblValue.getRow(iSelected);//lay ve dong duoc chon, va day vao textbox
        try {
            formData.setFieldValue("ISDN",
                                   vtRowData.elementAt(0).toString());
            formData.setFieldValue("IMSI",
                                   vtRowData.elementAt(1).toString());
	    formData.setFieldValue("Name",
				   vtRowData.elementAt(2).toString());
	    formData.setFieldValue("Birthday",
				   vtRowData.elementAt(3).toString());
	    formData.setFieldValue("Address",
				   vtRowData.elementAt(4).toString());
	    formData.setFieldValue("DateTime",
				   vtRowData.elementAt(5).toString());
//	    Status.setSelectedValue(StringUtil.nvl(vtRowData.elementAt(6).toString(),""));
	    formData.setFieldValue("Status",
				   vtRowData.elementAt(6).toString());

        } catch (Exception ex) {
            ex.printStackTrace();
            MessageBox.showMessageDialog(this, ex, Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
        }
    }

    public void clearDetailValue() {//Ham xoa trang du lieu tai cac field
        try {
            formData.setFieldValue("ISDN", "");
            formData.setFieldValue("IMSI", "");
	    formData.setFieldValue("Name", "");
	    formData.setFieldValue("Birthday", "");
            formData.setFieldValue("DateTime", "");
	    formData.setFieldValue("Status", "");
            formData.setFieldValue("Address", "");
        } catch (Exception ex) {
            ex.printStackTrace();
            MessageBox.showMessageDialog(this, ex, Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
        }
    }

    public void checkControlButton() {//Ham kiem tra nut duoc chon
        pnlButton.btnAdd.setEnabled(true);
        if (tblValue.getRowCount() <= 0) {//Neu nguoi dung khong chon truong nao thi dat an cac button
            pnlButton.btnAddCopy.setEnabled(false);
            pnlButton.btnModify.setEnabled(false);
            pnlButton.btnRemove.setEnabled(false);
        } else if (tblValue.getRowCount() > 0) {//nguoc lai nen ND chon
            pnlButton.btnAddCopy.setEnabled(true);
            pnlButton.btnModify.setEnabled(true);
            pnlButton.btnRemove.setEnabled(true);
        }
    }

    public void loadForm() {
        try {
            DataTransmit prmRequest = new DataTransmit();
            DataTransmit prmResponse = AppClient.sendRequest(
                    "telsoft.app.bean.ISDNBean",
                    "loadForm", prmRequest);

            Vector vtResult = (Vector) prmResponse.getReturn();
            int iSelected = tblValue.getSelectedRow();
            tblValue.setData(vtResult);//day du lieu vao bang
            if (tblValue.getRowCount() > 0) {

                if (iSelected < 0 || iSelected >= tblValue.getRowCount()) {
                    iSelected = 0;
                }
                tblValue.setRowSelectionInterval(iSelected, iSelected);
            }
            checkControlButton();
        } catch (Exception e) {
            e.printStackTrace();
            MessageBox.showMessageDialog(this, e, Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
        }
    }

    public boolean add() {//ham them du lieu vao database
        try {
            DataTransmit request = new DataTransmit();
	    //Lay gia tri tu form
            request.setString("mstrISDN", ISDN.getText().trim());
            request.setString("mstrIMSI", IMSI.getText().trim());
	    //day sang ben bean thuc hien truy van
            DataTransmit response = AppClient.sendRequest(
                    "telsoft.app.bean.ISDNBean", "insert", request);
            Vector vtData = new Vector();
	    //lay gia tri bean tra ve
            vtData.addElement(response.getString("mstrISDN"));
            vtData.addElement(response.getString("mstrIMSI"));
            vtData.addElement("");
	    vtData.addElement("");
	    vtData.addElement("");
	    vtData.addElement("");
	    vtData.addElement("Chưa kích hoạt");

            tblValue.addRow(vtData);
            if (tblValue.getRowCount() >
                0) {
                int iSelected = tblValue.
                                getRowCount() - 1;
                tblValue.
                        changeSelectedRow(iSelected);
            }
            checkControlButton();
        } catch (Exception e) {
            e.printStackTrace();
            MessageBox.showMessageDialog(this, e, Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
            ISDN.requestFocus();
            return false;
        }
        return true;
    }

    public boolean validateInput(int iOldAction, int iNewAction) {
        if (iOldAction == ACTION_NONE && (iNewAction == ACTION_ADD_COPY ||
                                          iNewAction == ACTION_MODIFY ||
                                          iNewAction == ACTION_REMOVE)) {
            if (tblValue.getSelectedRow() < 0) {
                return false;
            }//kiem tra neu nguoi dung chọn them, copy, sua doi va nhan luu thi gọi ham validate
        } else if ((iOldAction == ACTION_ADD || iOldAction == ACTION_ADD_COPY ||
                    iOldAction == ACTION_MODIFY) && iNewAction == ACTION_SAVE) {
            return validateInput();
        }
        return true;

    }

    public void onChangeAction(int iOldAction, int iNewAction) {
        if (iNewAction == ACTION_NONE) {
            formData.setFieldEnabled(false);
            tblValue.setEnabled(true);
            tblValue.requestFocus();
            checkControlButton();
        } else if (iNewAction == ACTION_SAVE || iNewAction == ACTION_CANCEL) {
            fillDetailValue();
            checkControlButton();
	    btnReport.setEnabled(true);
        } else if (iNewAction == ACTION_ADD || iNewAction == ACTION_MODIFY ||
                   iNewAction == ACTION_ADD_COPY) {
//            formData.setFieldEnabled(true);
	    ISDN.setEnabled(true);
	    IMSI.setEnabled(true);
            tblValue.setEnabled(false);
	    btnReport.setEnabled(false);
            checkControlButton();
            if (iNewAction == ACTION_ADD) {
                clearDetailValue();
            }
            ISDN.requestFocus();
        }

    }

    public void exit() {
        if (pnlButton.exit()) {
            dispose();
        }
    }


    public String getPermission() {
        return telsoft.admin.util.AppClient.getPermission(PermissionApp.
                FormISDN);
    }

    public boolean modify() {
        return false;
    }

    public boolean remove() {
        return false;
    }

    public boolean search() {
        return false;
    }
}
